package com.fordmotor.api;

import com.fordmotor.config.BaseConfig;
import com.fordmotor.pojo.AccessTokenVO;
import com.fordmotor.pojo.WxchatUser;
import com.fordmotor.service.WechatService;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import static com.fordmotor.cache.EhCache.cacheManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.UUID;
@Controller
public class LoginAPI {

    @Autowired
    private WechatService wechatService;

    @PostMapping(value = "/login")
    public String wxKfLoginPage(HttpServletRequest request) throws Exception {
        // 防止csrf攻击（跨站请求伪造攻击）
        String state = UUID.randomUUID().toString().replaceAll("-", "");
        HttpSession session = request.getSession();
        //存入session
        session.setAttribute("wechat-kf-state",state);
        //普通微信三方地址
        String url = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid="+ BaseConfig.getAppId() +
                "&redirect_uri="+BaseConfig.getRedirectUri()+
                "&response_type=code" +
                //"&scope=snsapi_userinfo" +
                "&scope=snsapi_base" +
                "&state="+state+
                "&code="+BaseConfig.getCode()+
                "#wechat_redirect";
        return "redirect:"+url;
    }

    @GetMapping("/callback")
    public String callback(HttpServletRequest request){
        //得到code用于交换token
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        //判断state是否合法
        //String stateStr = (String)request.getSession().getAttribute("wechat-kf-state");
        //||!state.equals(stateStr)
        if(StringUtils.isEmpty(code)||StringUtils.isEmpty(state)){
            request.setAttribute("msg","非法操作，请重新登录！");
            return "redirect:/error.html";
        }
        //用户授权后的code换取token
        AccessTokenVO token = wechatService.getAccessToken(code);

        //判断是否成功获取到了token
        if(token != null && token.getErrCode()!=null){
            request.setAttribute("msg","token获取失败,请重新登录");
            return "redirect:/error.html";
        }
        if(token == null || StringUtils.isEmpty(token.getAccessToken())||StringUtils.isEmpty((String)token.getOpenId())){
            request.setAttribute("msg","access_token拉取失败,请重新登录");
            return "redirect:/error.html";
        }
        //刷新accesstoken
        Map refreshToken = wechatService.refrehToken(BaseConfig.getAppId(),token.getRefreshToken());
        //使用token交换获取用户信息
        WxchatUser user = wechatService.getUserInfo(refreshToken);
        //将用户信息入栈
        request.setAttribute("user",user);
        Ehcache cache = cacheManager.getCache("member");
        Element e = cache.getQuiet(user.getOpenid());
        if (e == null){
            Element element = new Element(user.getOpenid(),user);
            cache.put(element);
        }
        return "redirect:/home.html";
    }



}
